<template>
	<view class="brand-manage">
		<!-- 顶部操作栏 -->
		<view class="operation-bar">
			<view class="search-section">
				<view class="search-box">
					<text class="search-icon iconfont icon-search"></text>
					<input v-model="searchKeyword" type="text" placeholder="搜索品牌名称" class="search-input" @confirm="handleSearch" />
					<text v-if="searchKeyword" class="clear-icon" @click="clearSearch">×</text>
				</view>
				<view class="filter-box">
					<picker
						mode="selector"
						:range="[
							{ name: '全部状态', value: '' },
							{ name: '已启用', value: '1' },
							{ name: '已停用', value: '0' },
						]"
						range-key="name"
						@change="handleStatusFilter"
					>
						<view class="filter-item">
							<text class="filter-text">{{ selectedStatus?.name || '状态筛选' }}</text>
							<text class="filter-icon iconfont icon-down"></text>
						</view>
					</picker>
					<picker
						mode="selector"
						:range="[
							{ name: '默认排序', value: 'default' },
							{ name: '名称升序', value: 'name_asc' },
							{ name: '名称降序', value: 'name_desc' },
						]"
						range-key="name"
						@change="handleSortChange"
					>
						<view class="filter-item">
							<text class="filter-text">{{ selectedSort?.name || '排序方式' }}</text>
							<text class="filter-icon iconfont icon-down"></text>
						</view>
					</picker>
				</view>
			</view>
			<view class="action-section">
				<button type="primary" class="add-btn" @click="handleAddBrand">
					<text class="btn-icon">+</text>
					新增品牌
				</button>
				<button type="default" class="batch-btn" @click="handleBatchOperation">批量操作</button>
			</view>
		</view>

		<!-- 品牌列表 -->
		<view class="brand-grid">
			<view v-for="item in brandList" :key="item.id" class="brand-card">
				<view class="card-header">
					<view class="brand-logo-container">
						<image :src="item.picUrl" mode="aspectFit" class="brand-logo" />
					</view>
					<text :class="['status-badge', item.status === 1 ? 'active' : 'inactive']">
						{{ item.status === 1 ? '已启用' : '已停用' }}
					</text>
				</view>
				<view class="card-body">
					<text class="brand-name">{{ item.name }}</text>
					<text class="brand-desc">{{ item.description || '暂无描述' }}</text>
				</view>
				<view class="card-footer">
					<view class="action-btns">
						<button type="primary" size="mini" class="action-btn edit" @click="handleEdit(item)">编辑</button>
						<button :type="item.status === 1 ? 'warning' : 'success'" size="mini" class="action-btn status" @click="handleStatusToggle(item)">
							{{ item.status === 1 ? '停用' : '启用' }}
						</button>
						<button type="default" size="mini" class="action-btn more" @click="handleShowMore(item, $event)">更多</button>
					</view>
				</view>
			</view>

			<view v-if="brandList.length === 0" class="empty-state">
				<image src="/static/images/empty.png" mode="aspectFit" class="empty-icon" />
				<text class="empty-text">暂无品牌数据</text>
				<button type="primary" size="mini" class="empty-btn" @click="handleAddBrand">添加第一个品牌</button>
			</view>
		</view>

		<!-- 分页器 -->
		<view class="pagination">
			<view class="page-info"> 共 {{ total }} 条记录 </view>
			<view class="page-btns">
				<button type="default" size="mini" :disabled="currentPage === 1" @click="handlePageChange(currentPage - 1)">上一页</button>
				<text class="page-number">{{ currentPage }} / {{ totalPages }}</text>
				<button type="default" size="mini" :disabled="isLastPage" @click="handlePageChange(currentPage + 1)">下一页</button>
			</view>
			<view class="page-size">
				<picker mode="selector" :range="[10, 20, 50]" :value="pageSizeIndex" @change="handlePageSizeChange">
					<view class="page-size-text"> {{ pageSize }}条/页 </view>
				</picker>
			</view>
		</view>

		<!-- 更多操作菜单 -->
		<view v-if="showMoreMenu" class="more-menu" :style="moreMenuStyle" @click.stop>
			<view class="menu-item copy" @click="handleCopy(selectedBrand)"> 复制品牌 </view>
			<view class="menu-item delete" @click="handleDelete(selectedBrand)"> 删除品牌 </view>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';
import type { BrandVO } from '@/api/product/brand';

// 状态定义
const searchKeyword = ref('');
const currentPage = ref(1);
const pageSize = ref(12);
const total = ref(0);
const isLastPage = ref(false);

// 筛选相关
const selectedStatus = ref<{ name: string; value: string }>();
const selectedSort = ref<{ name: string; value: string }>();

// 更多菜单相关
const showMoreMenu = ref(false);
const moreMenuPosition = ref({ x: 0, y: 0 });
const selectedBrand = ref<BrandVO>();

// 模拟数据
const brandList = ref<BrandVO[]>([
	{
		id: 1,
		name: 'Apple',
		picUrl: 'https://via.placeholder.com/200',
		description: '苹果公司是美国的一家高科技公司，专注于设计、开发和销售消费电子产品、计算机软件和在线服务。',
		sort: 1,
		status: 1,
	},
	{
		id: 2,
		name: 'Samsung',
		picUrl: 'https://via.placeholder.com/200',
		description: '三星集团是韩国最大的跨国企业集团，业务涉及电子、金融、机械、化学等多个领域。',
		sort: 2,
		status: 1,
	},
	{
		id: 3,
		name: 'Huawei',
		picUrl: 'https://via.placeholder.com/200',
		description: '华为技术有限公司是中国的一家跨国科技公司，专注于电信设备、智能手机和企业网络解决方案。',
		sort: 3,
		status: 0,
	},
	{
		id: 4,
		name: 'Xiaomi',
		picUrl: 'https://via.placeholder.com/200',
		description: '小米公司是中国的一家电子产品公司，生产智能手机、移动应用程序、笔记本电脑和相关消费电子产品。',
		sort: 4,
		status: 1,
	},
	{
		id: 5,
		name: 'Nike',
		picUrl: 'https://via.placeholder.com/200',
		description: '耐克是全球著名的体育用品制造商，以其运动鞋、服装、装备和配件而闻名。',
		sort: 5,
		status: 1,
	},
	{
		id: 6,
		name: 'Adidas',
		picUrl: 'https://via.placeholder.com/200',
		description: '阿迪达斯是德国的一家运动服装和鞋类制造商，是全球第二大运动用品制造商。',
		sort: 6,
		status: 0,
	},
]);

// 计算属性
const totalPages = computed(() => Math.ceil(total.value / pageSize.value));
const pageSizeIndex = computed(() => {
	const sizes = [10, 20, 50];
	return sizes.indexOf(pageSize.value);
});
const moreMenuStyle = computed(() => ({
	left: `${moreMenuPosition.value.x}px`,
	top: `${moreMenuPosition.value.y}px`,
}));

// 获取品牌列表
const loadBrandList = async () => {
	try {
		// 模拟API调用
		// const res = await getBrandPage({
		//   pageNo: currentPage.value,
		//   pageSize: pageSize.value,
		//   name: searchKeyword.value,
		//   status: selectedStatus.value?.value ? Number(selectedStatus.value.value) : undefined
		// })

		// 模拟数据
		let filteredList = [...brandList.value];

		// 应用搜索关键词过滤
		if (searchKeyword.value) {
			filteredList = filteredList.filter((item) => item.name.toLowerCase().includes(searchKeyword.value.toLowerCase()));
		}

		// 应用状态过滤
		if (selectedStatus.value?.value) {
			filteredList = filteredList.filter((item) => item.status === Number(selectedStatus.value?.value));
		}

		// 应用排序
		if (selectedSort.value?.value) {
			switch (selectedSort.value.value) {
				case 'name_asc':
					filteredList.sort((a, b) => a.name.localeCompare(b.name));
					break;
				case 'name_desc':
					filteredList.sort((a, b) => b.name.localeCompare(a.name));
					break;
				default:
					filteredList.sort((a, b) => a.sort - b.sort);
			}
		}

		total.value = filteredList.length;

		// 模拟分页
		const start = (currentPage.value - 1) * pageSize.value;
		const end = start + pageSize.value;
		filteredList = filteredList.slice(start, end);

		brandList.value = filteredList;
		isLastPage.value = currentPage.value * pageSize.value >= total.value;
	} catch (error) {
		uni.showToast({
			title: '获取品牌列表失败',
			icon: 'none',
		});
	}
};

// 搜索相关处理
const handleSearch = () => {
	currentPage.value = 1;
	loadBrandList();
};

const clearSearch = () => {
	searchKeyword.value = '';
	handleSearch();
};

const handleStatusFilter = (e: any) => {
	const options = [
		{ name: '全部状态', value: '' },
		{ name: '已启用', value: '1' },
		{ name: '已停用', value: '0' },
	];
	selectedStatus.value = options[e.detail.value];
	currentPage.value = 1;
	loadBrandList();
};

const handleSortChange = (e: any) => {
	const options = [
		{ name: '默认排序', value: 'default' },
		{ name: '名称升序', value: 'name_asc' },
		{ name: '名称降序', value: 'name_desc' },
	];
	selectedSort.value = options[e.detail.value];
	loadBrandList();
};

// 分页处理
const handlePageChange = (page: number) => {
	if (page < 1 || (isLastPage.value && page > currentPage.value)) return;
	currentPage.value = page;
	loadBrandList();
};

const handlePageSizeChange = (e: any) => {
	const sizes = [10, 20, 50];
	pageSize.value = sizes[e.detail.value];
	currentPage.value = 1;
	loadBrandList();
};

// 品牌操作处理
const handleAddBrand = () => {
	uni.navigateTo({
		url: '/pages/product/views/brand-edit',
	});
};

const handleEdit = (item: BrandVO) => {
	uni.navigateTo({
		url: `/pages/product/views/brand-edit?id=${item.id}`,
	});
};

const handleStatusToggle = async (item: BrandVO) => {
	try {
		// 模拟API调用
		// await updateBrandStatus({
		//   id: item.id!,
		//   status: item.status === 1 ? 0 : 1
		// })

		// 直接更新本地数据
		item.status = item.status === 1 ? 0 : 1;

		uni.showToast({
			title: '状态更新成功',
			icon: 'success',
		});
	} catch (error) {
		uni.showToast({
			title: '状态更新失败',
			icon: 'none',
		});
	}
};

const handleDelete = async (item?: BrandVO) => {
	if (!item) return;

	uni.showModal({
		title: '确认删除',
		content: `确定要删除品牌"${item.name}"吗？`,
		success: async (res) => {
			if (res.confirm) {
				try {
					// 模拟API调用
					// await deleteBrand(item.id!)

					// 直接更新本地数据
					const index = brandList.value.findIndex((brand) => brand.id === item.id);
					if (index !== -1) {
						brandList.value.splice(index, 1);
					}

					showMoreMenu.value = false;

					uni.showToast({
						title: '删除成功',
						icon: 'success',
					});

					// 如果当前页没有数据了，且不是第一页，则返回上一页
					if (brandList.value.length === 0 && currentPage.value > 1) {
						currentPage.value--;
						loadBrandList();
					}
				} catch (error) {
					uni.showToast({
						title: '删除失败',
						icon: 'none',
					});
				}
			}
		},
	});
};

// 更多菜单相关处理
const handleShowMore = (item: BrandVO, event: any) => {
	const { clientX, clientY } = event;
	moreMenuPosition.value = { x: clientX, y: clientY };
	selectedBrand.value = item;
	showMoreMenu.value = true;
};

const handleCopy = (item?: BrandVO) => {
	if (!item) return;

	showMoreMenu.value = false;

	// 创建一个新的品牌对象，复制原品牌的信息
	const newBrand = {
		...item,
		id: Math.max(...brandList.value.map((brand) => brand.id || 0)) + 1,
		name: `${item.name} (复制)`,
		sort: Math.max(...brandList.value.map((brand) => brand.sort || 0)) + 1,
	};

	// 添加到列表中
	brandList.value.push(newBrand);

	uni.showToast({
		title: '复制成功',
		icon: 'success',
	});

	// 重新加载列表
	loadBrandList();
};

const handleBatchOperation = () => {
	uni.showActionSheet({
		itemList: ['批量启用', '批量停用', '批量删除'],
		success: (res) => {
			// TODO: 实现批量操作功能
			uni.showToast({
				title: '批量操作功能开发中',
				icon: 'none',
			});
		},
	});
};

// 点击页面任意位置关闭更多菜单
const handlePageClick = () => {
	if (showMoreMenu.value) {
		showMoreMenu.value = false;
	}
};

// 生命周期
onMounted(() => {
	// 设置总数
	total.value = brandList.value.length;

	loadBrandList();

	// 添加点击事件监听
	document.addEventListener('click', handlePageClick);
});

onUnmounted(() => {
	// 移除点击事件监听
	document.removeEventListener('click', handlePageClick);
});
</script>

<style lang="scss">
.brand-manage {
	padding: 20rpx;
	background-color: #f5f7fa;
	min-height: 100vh;

	.operation-bar {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
		gap: 20rpx;

		.search-section {
			display: flex;
			flex-wrap: wrap;
			gap: 20rpx;
			flex: 1;

			.search-box {
				position: relative;
				flex: 1;
				min-width: 300rpx;

				.search-icon {
					position: absolute;
					left: 20rpx;
					top: 50%;
					transform: translateY(-50%);
					color: #909399;
					font-size: 28rpx;
				}

				.search-input {
					width: 80%;
					height: 72rpx;
					border: 1px solid #dcdfe6;
					border-radius: 36rpx;
					padding: 0 60rpx;
					font-size: 28rpx;
					background-color: #f5f7fa;
					transition: all 0.3s ease;

					&:focus {
						border-color: #409eff;
						background-color: #fff;
					}
				}

				.clear-icon {
					position: absolute;
					right: 20rpx;
					top: 50%;
					transform: translateY(-50%);
					color: #909399;
					font-size: 32rpx;
					cursor: pointer;
				}
			}

			.filter-box {
				display: flex;
				gap: 20rpx;

				.filter-item {
					height: 72rpx;
					border: 1px solid #dcdfe6;
					border-radius: 4rpx;
					padding: 0 20rpx;
					display: flex;
					align-items: center;
					gap: 10rpx;
					background-color: #fff;
					cursor: pointer;

					.filter-text {
						font-size: 28rpx;
						color: #606266;
					}

					.filter-icon {
						font-size: 24rpx;
						color: #909399;
					}
				}
			}
		}

		.action-section {
			display: flex;
			gap: 20rpx;

			.add-btn,
			.batch-btn {
				margin: 0;
				height: 72rpx;
				line-height: 72rpx;
				font-size: 28rpx;
				display: flex;
				align-items: center;
				justify-content: center;
			}

			.add-btn {
				.btn-icon {
					margin-right: 10rpx;
					font-size: 32rpx;
				}
			}
		}
	}

	.brand-grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(300rpx, 1fr));
		gap: 20rpx;
		margin-bottom: 20rpx;

		.brand-card {
			background-color: #fff;
			border-radius: 8rpx;
			overflow: hidden;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
			transition: all 0.3s ease;
			display: flex;
			flex-direction: column;

			&:hover {
				transform: translateY(-2rpx);
				box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.15);
			}

			.card-header {
				position: relative;
				padding-top: 100%; /* 1:1 宽高比 */

				.brand-logo-container {
					position: absolute;
					top: 0;
					left: 0;
					width: 100%;
					height: 100%;
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 20rpx;
					background-color: #f5f7fa;
				}

				.brand-logo {
					max-width: 100%;
					max-height: 100%;
					object-fit: contain;
				}

				.status-badge {
					position: absolute;
					top: 20rpx;
					right: 20rpx;
					padding: 4rpx 16rpx;
					border-radius: 20rpx;
					font-size: 24rpx;
					z-index: 1;

					&.active {
						background-color: #f0f9eb;
						color: #67c23a;
					}

					&.inactive {
						background-color: #f4f4f5;
						color: #909399;
					}
				}
			}

			.card-body {
				padding: 20rpx;
				flex: 1;
				display: flex;
				flex-direction: column;
				gap: 10rpx;

				.brand-name {
					font-size: 32rpx;
					font-weight: bold;
					color: #303133;
				}

				.brand-desc {
					font-size: 24rpx;
					color: #909399;
					line-height: 1.5;
					overflow: hidden;
					text-overflow: ellipsis;
					display: -webkit-box;
					-webkit-line-clamp: 2;
					-webkit-box-orient: vertical;
				}
			}

			.card-footer {
				padding: 20rpx;
				border-top: 1px solid #ebeef5;

				.action-btns {
					display: flex;
					justify-content: space-between;
					gap: 10rpx;

					.action-btn {
						flex: 1;
						margin: 0;
						font-size: 24rpx;

						&.edit {
							background-color: #409eff;
							border-color: #409eff;
						}

						&.status {
							&[type='warning'] {
								background-color: #e6a23c;
								border-color: #e6a23c;
							}

							&[type='success'] {
								background-color: #67c23a;
								border-color: #67c23a;
							}
						}
					}
				}
			}
		}
	}

	.empty-state {
		background-color: #fff;
		border-radius: 8rpx;
		padding: 60rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
		grid-column: 1 / -1;

		.empty-icon {
			width: 200rpx;
			height: 200rpx;
			opacity: 0.5;
		}

		.empty-text {
			font-size: 28rpx;
			color: #909399;
			margin-bottom: 20rpx;
		}
	}

	.pagination {
		background-color: #fff;
		padding: 20rpx;
		border-radius: 8rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

		.page-info {
			font-size: 24rpx;
			color: #909399;
		}

		.page-btns {
			display: flex;
			align-items: center;
			gap: 20rpx;

			button {
				margin: 0;
				font-size: 24rpx;

				&[disabled] {
					background-color: #f5f7fa;
					border-color: #dcdfe6;
					color: #c0c4cc;
				}
			}

			.page-number {
				font-size: 24rpx;
				color: #606266;
			}
		}

		.page-size {
			.page-size-text {
				font-size: 24rpx;
				color: #606266;
				padding: 10rpx 20rpx;
				border: 1px solid #dcdfe6;
				border-radius: 4rpx;
				cursor: pointer;

				&:hover {
					border-color: #c0c4cc;
				}
			}
		}
	}

	.more-menu {
		position: fixed;
		background-color: #fff;
		border-radius: 4rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
		z-index: 100;
		min-width: 160rpx;

		.menu-item {
			padding: 20rpx 30rpx;
			font-size: 28rpx;
			cursor: pointer;
			transition: all 0.3s ease;

			&:hover {
				background-color: #f5f7fa;
			}

			&.copy {
				color: #409eff;
			}

			&.delete {
				color: #f56c6c;
			}
		}
	}
}
</style>
